﻿using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MYData.Core.EFDbContext;
using Microsoft.EntityFrameworkCore;
using MYData.Core.Extensions;

namespace MYData.Core.DBManager
{
    public static class Extensions
    {
        //执行select的自定义扩展属性
        public static List<dynamic> GetList(this DbContext db, string sql)
    {
        try
        {
                DbConnection conn = db.Database.GetDbConnection();
                if (conn.State == ConnectionState.Closed)
                {
                    conn.Open();
                }
                using (DbCommand cmd = conn.CreateCommand())
                {
                    cmd.CommandText = sql;
                    //cmd.Parameters.AddRange(parameters);
                    DataTable dt = new DataTable();

                    using (DbDataReader reader = cmd.ExecuteReader())
                    {
                        dt.Load(reader);
                    }
                    cmd.Parameters.Clear();
                    conn.Close();
                    if (dt.Rows.Count <= 0)
                        return null;
                    string json = dt.ToJson();
                    List<dynamic> list = Newtonsoft.Json.JsonConvert.DeserializeObject<List<dynamic>>(json);
                    return list;
                }
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);
        }
    }
}
}
